<?php
/*
 * @Author: fk 1031041088@qq.com
 * @Date: 2024-12-11 21:30:55
 * @LastEditors: fk 1031041088@qq.com
 * @LastEditTime: 2024-12-11 23:10:15
 */
require_once '../config/oss_config.php';
require_once '../config/database.php';

// 引入OSS命名空间
use OSS\OssClient;
use OSS\Core\OssException;

header('Content-Type: application/json');

try {
    // 分页参数
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;
    
    // 获取总数
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM images");
    $total = $stmt->fetch()['total'];
    
    // 获取分页数据
    $stmt = $pdo->prepare("SELECT * FROM images ORDER BY created_at DESC LIMIT ? OFFSET ?");
    $stmt->bindValue(1, $limit, PDO::PARAM_INT);
    $stmt->bindValue(2, $offset, PDO::PARAM_INT);
    $stmt->execute();
    $images = $stmt->fetchAll();
    
    // 获取浏览次数
    $stmt = $pdo->prepare("SELECT view_count FROM page_views WHERE page_id = ?");
    $stmt->execute(['preview_page']);
    $viewCount = $stmt->fetch()['view_count'] ?? 0;
    
    // 为每个图片生成签名URL
    $ossClient = new OssClient(
        OSS_ACCESS_KEY_ID,
        OSS_ACCESS_KEY_SECRET,
        OSS_ENDPOINT
    );
    
    $imageList = [];
    foreach($images as $image) {
        $imageList[] = [
            'id' => $image['id'],
            'filename' => $image['filename'],
            'url' => $ossClient->signUrl(OSS_BUCKET, $image['oss_path'], 3600),
            'created_at' => $image['created_at']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'images' => $imageList,
        'view_count' => $viewCount,
        'total' => $total,
        'has_more' => ($offset + $limit) < $total
    ]);
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?> 